CSS Gradient Border
Published: 02.01.2022, last edit: 29.02.2024
Let's say we would like to give our <div>-element a 2px wide gradient border. To achieve this we can use the ::before selector like so:
.box {
max-width: 250px;
height: 50px;
border-radius: 20px; /* 22px - 2px */
position: relative; /*necessary*/
background-color: #fff;
margin-left: auto;
margin-right: auto;
}
.box::before {
border-radius: 22px;
content: '';
background-image: linear-gradient(135deg, #00d2ff, #3a7bd5);
padding: 2px;
width: 100%;
height: 100%;
top: -2px;
left: -2px;
position: absolute;
z-index: -1;
}
It is important to set the position to relative and to specify a background-color to overwrite the properties of the ::before selector.
Note that it looks better to set the border-radius of the inner box smaller than the border-radius of the outer box with the ::before selector.
A good rule for this is: inner radius = outer radius - padding.
The result will look like this:
Sources
| [1] |
Stack Overflow |